package dang.action.user;

import java.io.PrintWriter;
import java.io.Serializable;

import dang.action.DangAction;
import dang.common.DigestUtil;
import dang.common.EmailUtil;
import dang.common.VerifyUtil;
import dang.dao.DaoFactory;
import dang.dao.UserDao;
import dang.entity.User;
import dang.exception.DangException;


public class RegisterAction extends DangAction implements Serializable{
	private User user;
	private String validateCode;
	/**
	 * 
	 */
	public String execute() throws Exception{
		String code=(String) session.get("validateCode");
		
//		verifyEmail();//不能使用此方法验证邮箱，一return就会调用result视图
		if(!code.equalsIgnoreCase(validateCode)){
			return "registerError";
		}
		
		UserDao userDao = DaoFactory.getUserDao();
		
		try {
			if("".equals(user.getEmail())||!userDao.verifyEmail(user.getEmail()).equals("emailKeyong"))
				return "registerError";
			//1.将用户信息写入d_user表
			//将密码加密
			String pass = DigestUtil.md5(user.getPassword());
			user.setPassword(pass);
			userDao.save(user);
			//2.生成邮箱激活码
			code = VerifyUtil.generateCode(user.getId());
			//3.给用户发送邮件
			EmailUtil.send(user.getEmail(), code);
			//4.将激活码uuid部分更新到d_user表
			String uuid = VerifyUtil.getUUID(code);
			user.setEmail_verify_code(uuid+"-"+user.getId());
			user.setIs_email_verify(0);
			userDao.updateVerifyState(user);
			//注册后验证码无效
			session.put("validateCode", "你是猪");
			return "next";
		} catch (DangException e) {
			e.printStackTrace();
			throw new Exception(e);
		}
	}
	
	public String verifyEmail() throws Exception{
		UserDao dao= DaoFactory.getUserDao();
		String rs = dao.verifyEmail(user.getEmail());
		response.setContentType("text/json;charset=utf-8");
		PrintWriter pw=response.getWriter();
		if("emailKeyong".equals(rs)){
			pw.print("true");
		}else{
			pw.print("false");
		}
		pw.close();
		return "success";
	}
	/**
	 * 验证码的验证
	 * @throws Exception
	 */
	public String verifyValidateCode() throws Exception{
		String code=(String) session.get("validateCode");
		response.setContentType("text/json;charset=utf-8");
		PrintWriter pw=response.getWriter();
		if(code.equals(validateCode)){
			pw.print("true");
		}else{
			pw.print("false");
		}
		pw.close();
		return "verifyValidateCodeOk";
	}
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	public String getValidateCode() {
		return validateCode;
	}

	public void setValidateCode(String validateCode) {
		this.validateCode = validateCode;
	}

	
	
}
